import * as api from '../../api/common';

Page({
  data: {
    year: '',
    month: '',
    day: '',
    date: '',
    currentDate: ''
  },

  onLoad() {
    const userInfo = tt.getStorageSync('info');
    if (userInfo && userInfo.birthday) {
      this.setData({ date: userInfo.birthday });
    }
    this.initDateComponents(this.data.date);
    this.setData({ currentDate: this.getCurrentDate() });
  },

  bindDateChange(e) {
    const selectedDate = e.detail.value;
    this.setData({
      date: selectedDate
    });
    this.initDateComponents(selectedDate);
  },

  initDateComponents(dateString) {
    const [year, month, day] = dateString.split('-');
    this.setData({
      year,
      month,
      day
    });
  },

  getCurrentDate() {
    const today = new Date();
    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, '0');
    const day = String(today.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  },

  async updateBirthday() {
    if (!this.data.date) {
      tt.showToast({
        title: '请选择出生日期',
        icon: 'none'
      });
      return;
    }

    try {
      const userInfo = tt.getStorageSync('info');
      if (userInfo && userInfo.id) {
        const response = await api.updateUserInfo({
          id: userInfo.id,
          birthday: this.data.date,
        });

        if (response.code !== 0) {
          tt.showToast({
            title: '生日更新成功',
            icon: 'success'
          });
          userInfo.birthday = this.data.date; // 更新本地存储中的用户信息
          tt.setStorageSync('info', userInfo);
          tt.navigateBack(); // 返回上一页
        } else {
          tt.showToast({
            title: response.msg,
            icon: 'none'
          });
        }
      }
    } catch (error) {
      tt.showToast({
        title: error,
        icon: 'none'
      });
    }
  }
});
